package service

import (
	"fmt"
	"net/http"
	"sync"
)

type Client struct {
	ID   string
	Chan chan string
}

type SSEService struct {
	clients map[string]*Client
	mu      sync.RWMutex
}

func NewSSEService() *SSEService {
	return &SSEService{
		clients: make(map[string]*Client),
	}
}

func (s *SSEService) HandleSSE(w http.ResponseWriter, r *http.Request) {
	// 设置SSE必要的响应头
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// 为新客户端创建一个通道
	clientChan := make(chan string)
	clientID := r.RemoteAddr

	// 注册新客户端
	s.registerClient(clientID, clientChan)
	defer s.removeClient(clientID)

	// 保持连接直到客户端断开
	notify := r.Context().Done()
	go func() {
		<-notify
		s.removeClient(clientID)
	}()

	// 发送SSE消息
	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "SSE not supported", http.StatusInternalServerError)
		return
	}

	// 发送初始连接成功消息
	fmt.Fprintf(w, "data: %s\n\n", "Connected successfully")
	flusher.Flush()

	for {
		select {
		case <-notify:
			return
		case msg := <-clientChan:
			fmt.Fprintf(w, "data: %s\n\n", msg)
			flusher.Flush()
		}
	}
}

func (s *SSEService) registerClient(clientID string, ch chan string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.clients[clientID] = &Client{
		ID:   clientID,
		Chan: ch,
	}
}

func (s *SSEService) removeClient(clientID string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if client, exists := s.clients[clientID]; exists {
		close(client.Chan)
		delete(s.clients, clientID)
	}
}

// Broadcast 广播消息给所有连接的客户端
func (s *SSEService) Broadcast(message string) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	
	for _, client := range s.clients {
		select {
		case client.Chan <- message:
		default:
			// 如果客户端无法接收消息，跳过
		}
	}
}

// 添加一个导出的方法用于语音唤醒时广播消息
func (s *SSEService) NotifyWakeup(wakeupMsg string) {
	s.Broadcast(fmt.Sprintf("语音唤醒: %s", wakeupMsg))
} 